<script setup lang="ts">
  import { computed, PropType, ref, watch } from 'vue'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { saveUpdateWorkUser } from '@/api/order'
  import { FormInstance } from 'element-plus'
  import { useGetReplaceCustomers } from '@/services/module/order/useDetail'
  import { useGetMainContactPersonOptionList } from '@/services/pages/user/useUser'
  import { debounce } from 'lodash'

  const {
    optionList: sendRepairUserOptionList,
    getOptionListLoading: getSendRepairUserOptionListLoading,
    getOptionListParam: getSendRepairUserOptionListParam,
    getOptionList: getSendRepairUserOptionList,
  } = useGetMainContactPersonOptionList()
  const {
    replaceCustomers,
    getReplaceCustomersKeyword,
    getReplaceCustomersLoading,
    getReplaceCustomers,
  } = useGetReplaceCustomers()

  defineOptions({
    name: 'UpdateOrderCustomerInfoModal',
  })

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 报单公司弹出框显示状态
  const sendRepairUserSelectPopoverVisible = ref(false)

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 地址选择组件实例
  const singleAddressInstance = ref<InstanceType<typeof SingleAddress> | null>(null)

  const loading = ref(false)

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 表单
  const formData = ref<OrderDetailAPiRequest.OrderCustomerUpdateForm>({
    address: '',
    area: '',
    city: '',
    helpOtherCreateOrder: false,
    name: '',
    otherPhone: '',
    phone: '',
    province: '',
    town: '',
    repairCompany: '',
    repairCompanyUserId: '',
    repairCompanyPhone: '',
    sendForRepairPhone: '',
    sendForRepairUsername: '',
    userId: '',
    id: '',
  })

  // 地址回显
  const echoAddress = computed(() => {
    return {
      province: formData.value.province,
      city: formData.value.city,
      area: formData.value.area,
      town: formData.value.town,
    }
  })

  // 表单校验规则
  const rules = ref({
    name: [{ required: true, message: '请输入公司名称', trigger: ['blur', 'change'] }],
    // address: [{ required: true, message: '请输入详细地址', trigger: ['blur', 'change'] }],
    // province: [
    //   { required: true, message: '请选择公司地址', trigger: ['blur', 'change'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       const { province, city, area } = formData.value
    //       if (!province || !city || !area) {
    //         callback(new Error('请选择公司地址'))
    //         return
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
    // phone: [
    //   { required: true, message: '请输入公司手机号', trigger: ['change', 'blur'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!verifyPhone(formData.value.phone)) {
    //         callback(new Error('手机号格式错误'))
    //         return
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
  })

  // 客户替换表格弹出框显示状态
  const replaceTablePopoverVisible = ref(false)

  /**
   * 关闭弹窗
   */
  const close = () => {
    if (singleAddressInstance.value) {
      singleAddressInstance.value.clearAddress()
    }
    formData.value = {
      address: '',
      area: '',
      city: '',
      helpOtherCreateOrder: false,
      name: '',
      otherPhone: '',
      phone: '',
      province: '',
      town: '',
      repairCompany: '',
      repairCompanyUserId: '',
      repairCompanyPhone: '',
      sendForRepairPhone: '',
      sendForRepairUsername: '',
      userId: '',
      id: '',
    }
    visible.value = false
    replaceTablePopoverVisible.value = false
  }

  /**
   * 保存事件
   */
  const onSave = async () => {
    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        loading.value = true
        const res = await saveUpdateWorkUser(formData.value)
        loading.value = false
        if (res.data.code === 20000) {
          visible.value = false
          HMessage.success('修改成功')
          emits('update')
        } else {
          HMessageBox.error(res.data.message)
        }
      } catch (error) {
        // e
      }
    }
  }

  /**
   * 获取更新之前的公司信息
   */
  const getCustomerInfoBeforeUpdate = async () => {
    // loading.value = true
    // const res = await getBeforeUpdateWorkUserInfo(props.orderDetail.id)
    // loading.value = false
    // if (res.data.code == 20000) {
    //   formData.value.address = res.data.data.row.address
    //   formData.value.area = res.data.data.row.area
    //   formData.value.city = res.data.data.row.city
    //   formData.value.name = res.data.data.row.name
    //   formData.value.province = res.data.data.row.province
    //   formData.value.phone = res.data.data.row.phone
    //   formData.value.otherPhone = res.data.data.row.otherPhone
    // } else {
    //   HMessageBox.error(res.data.message)
    // }
    formData.value = {
      address: props.orderDetail.address,
      area: props.orderDetail.area,
      city: props.orderDetail.city,
      helpOtherCreateOrder: false,
      name: props.orderDetail.name,
      otherPhone: props.orderDetail.otherPhone,
      phone: props.orderDetail.phone,
      province: props.orderDetail.province,
      town: props.orderDetail.town,
      repairCompany: props.orderDetail.repairCompany,
      repairCompanyUserId: props.orderDetail.repairCompanyUserId,
      repairCompanyPhone: props.orderDetail.repairCompanyPhone,
      sendForRepairPhone: props.orderDetail.sendForRepairPhone,
      sendForRepairUsername: props.orderDetail.sendForRepairUsername,
      userId: props.orderDetail.userId,
      id: props.orderDetail.id,
    }
  }

  /**
   * 地址更新事件
   * @param {Object} _address - 选择地址
   */
  const handleChangeAddress = (_address: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    formData.value.province = _address.province
    formData.value.city = _address.city
    formData.value.area = _address.area
    formData.value.town = _address.town
  }

  const _newCustomerQuery = async () => {
    const res = await getReplaceCustomers()
    if (res) {
      if (res.code !== 20000) {
        HMessageBox.error(res.message)
        return
      }

      if (replaceCustomers.value.length === 1) {
        handleReplaceCustomerClick(replaceCustomers.value[0])
        return
      }

      replaceTablePopoverVisible.value = true
    }
  }

  const handleReplaceCustomerClick = (customer: OrderDetailAPIResponse.ReplaceCustomer) => {
    Object.assign(formData.value, {
      name: customer.username,
      province: customer.province,
      city: customer.city,
      area: customer.area,
      address: customer.address,
      userId: customer.userId,
      phone: customer.phone,
    })
    getReplaceCustomersKeyword.value = ''
    replaceTablePopoverVisible.value = false
  }

  /**
   * 清除报单公司信息事件
   */
  const onClearSendRepairUserInfo = () => {
    formData.value.repairCompanyUserId = ''
    formData.value.repairCompany = ''
    formData.value.repairCompanyPhone = ''
  }

  /**
   * 报单公司输入事件
   */
  const handleSendRepairUserInput = debounce((keyword: string) => {
    if (keyword.trim()) {
      sendRepairUserSelectPopoverVisible.value = true
      getSendRepairUserOptionListParam.value.name = formData.value.repairCompany
      getSendRepairUserOptionList()
    }
  }, 500)

  /**
   * 报单公司更新事件
   * @param {UserMainContactPersonOption} sendRepairUser - 报单公司
   */
  const handleSendRepairUserChange = (sendRepairUser: UserMainContactPersonOption) => {
    formData.value.repairCompany = sendRepairUser.name
    formData.value.repairCompanyUserId = sendRepairUser.userId
    formData.value.repairCompanyPhone = sendRepairUser.phone
  }

  watch(
    visible,
    (value) => {
      if (value) {
        getCustomerInfoBeforeUpdate()
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    :loading="loading"
    title="修改报单公司信息"
    :width="800"
    unit="px"
    @click="replaceTablePopoverVisible = false"
    @close="close"
  >
    <el-form
      ref="formInstance"
      class="modal_form_content"
      label-position="top"
      :model="formData"
      :rules="rules"
      inline-message
    >
      <el-popover placement="bottom-end" :width="600" :visible="replaceTablePopoverVisible">
        <template #reference>
          <el-form-item label="新客户查询" @click.stop="">
            <div class="new-customer-query">
              <el-input
                v-model.trim="getReplaceCustomersKeyword"
                placeholder="请输入客户名称"
                @keyup.enter="_newCustomerQuery"
              />
              <h-button
                type="primary"
                :loading="getReplaceCustomersLoading"
                @click="_newCustomerQuery"
              >
                搜索
              </h-button>
            </div>
          </el-form-item>
        </template>

        <el-table
          :border="true"
          max-height="300"
          :data="replaceCustomers"
          @row-click="handleReplaceCustomerClick"
        >
          <el-table-column label="序号" width="50" type="index" :align="'center'" />
          <el-table-column show-overflow-tooltip label="客户名称" min-width="100" prop="username" />
          <el-table-column show-overflow-tooltip label="编号" width="120" prop="code" />
          <el-table-column label="手机号" width="110" prop="phone" />
          <!-- <el-table-column show-overflow-tooltip label="省" width="80" prop="province" />
          <el-table-column show-overflow-tooltip label="市" width="80" prop="city" />
          <el-table-column show-overflow-tooltip label="区" width="80" prop="area" />
          <el-table-column show-overflow-tooltip label="详细地址" width="100" prop="address" /> -->
        </el-table>
      </el-popover>

      <!--客户名称-->
      <el-form-item label="客户名称" prop="name">
        <el-input v-model.trim="formData.name" disabled clearable />
      </el-form-item>

      <!--客户手机号-->
      <el-form-item label="客户手机号" prop="phone">
        <el-input
          v-model.trim="formData.phone"
          clearable
          disabled
          maxlength="11"
          placeholder="请输入客户手机号"
          @input="formData.phone = formData.phone.replace(/[^0-9]/g, '')"
        />
      </el-form-item>

      <!-- 所属地区 -->
      <el-form-item label="所属地区" prop="province">
        <single-address disabled :address="echoAddress" @change="handleChangeAddress" />
      </el-form-item>

      <!--详细地址-->
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model.trim="formData.address"
          disabled
          placeholder="请输入详细地址"
          show-word-limit
          type="textarea"
          resize="both"
          maxlength="200"
        />
      </el-form-item>

      <!--报单公司-->
      <el-form-item label="报单公司" prop="repairCompany">
        <el-popover :visible="sendRepairUserSelectPopoverVisible" :width="370">
          <template #reference>
            <el-input
              v-model.trim="formData.repairCompany"
              placeholder="请输入报单公司"
              clearable
              @clear="onClearSendRepairUserInfo"
              @input="handleSendRepairUserInput"
              @blur="sendRepairUserSelectPopoverVisible = false"
            />
          </template>

          <el-table
            v-loading="getSendRepairUserOptionListLoading"
            :max-height="300"
            :border="true"
            :data="sendRepairUserOptionList"
            @row-click="handleSendRepairUserChange"
          >
            <!-- 序号 -->
            <el-table-column label="序号" type="index" :width="50" />

            <!-- 报单公司名称 -->
            <el-table-column
              label="报单公司名称"
              :min-width="100"
              show-overflow-tooltip
              prop="name"
            />

            <!-- 报单公司电话 -->
            <el-table-column label="报单公司电话" :width="120" show-overflow-tooltip prop="phone" />
          </el-table>
        </el-popover>
        <!-- <el-input v-model.trim="formData.repairCompany" clearable /> -->
      </el-form-item>

      <!--报单公司电话-->
      <el-form-item label="报单公司电话" prop="repairCompanyPhone">
        <el-input
          v-model.trim.number="formData.repairCompanyPhone"
          clearable
          maxlength="11"
          placeholder="请输入报单公司电话"
        />
      </el-form-item>

      <!--报单人信息-->
      <el-form-item label="报单人信息" prop="sendForRepairUsername">
        <el-input v-model.trim="formData.sendForRepairUsername" clearable />
      </el-form-item>

      <!--报单人电话-->
      <el-form-item label="报单人电话" prop="sendForRepairPhone">
        <el-input
          v-model.trim.number="formData.sendForRepairPhone"
          clearable
          maxlength="11"
          placeholder="请输入报单人电话"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <h-button is-modal type="primary" @click="onSave">保存</h-button>
      <h-button is-modal @click="close">关闭</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .new-customer-query {
    display: flex;
    column-gap: 8px;
    width: 100%;
  }
</style>
